package com.yunxin.download.server.infra.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.utils.JacksonUtils;
import com.yunxin.download.server.service.extenal.FileExportConfigDTO;
import com.yunxin.download.server.infra.constant.FileExportConstant;
import com.yunxin.download.server.infra.constant.enums.DownloadResultCode;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zero°
 * @since 2023-06-16
 */
@Slf4j
public enum TemplateFileUtils {

    /**
     * 实例
     */
    X;

    private static final String EXPORT_REPLACE_FLAG = "##";
    private static final String EXPORT_FLAG = "{." + EXPORT_REPLACE_FLAG + "}";


    /**
     * 检查json格式
     * @param jsonStr jsonStr
     * @param typeReference typeReference
     */
    public void validateJson(String jsonStr, TypeReference<?> typeReference) {
        try {
            JacksonUtils.X.parse(jsonStr, typeReference);
        } catch (Exception e) {
            throw new BusinessException(DownloadResultCode.JSON_ERROR);
        }
    }

    /**
     * 生成模板文件
     * @param exportConfig exportConfig
     * @param ossKey ossKey
     */
    public void createExportTemplate(String exportConfig, String ossKey) {
        //生成文件 项目类型
        List<FileExportConfigDTO> fileExportConfigs = JacksonUtils.X.parse(exportConfig, new TypeReference<List<FileExportConfigDTO>>() {
        });
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            List<List<String>> headers = new ArrayList<>(fileExportConfigs.size());
            List<String> fieldFlagNames = new ArrayList<>(fileExportConfigs.size());
            for (final FileExportConfigDTO excelExportConfigDTO : fileExportConfigs) {
                final String colName = excelExportConfigDTO.getColName();
                final String fieldName = excelExportConfigDTO.getFieldName();
                final List<FileExportConfigDTO> collections = excelExportConfigDTO.getCollections();
                if (collections != null && !collections.isEmpty()) {
                    //目前只支持两列  复合列
                    for (final FileExportConfigDTO childCol : collections) {
                        final String childColName = childCol.getColName();
                        final String childColFieldName = childCol.getFieldName();
                        headers.add(CollUtil.newArrayList(colName, childColName));
                        fieldFlagNames.add(EXPORT_FLAG.replace(EXPORT_REPLACE_FLAG, childColFieldName));
                    }
                } else {
                    headers.add(CollUtil.newArrayList(colName));
                    fieldFlagNames.add(EXPORT_FLAG.replace(EXPORT_REPLACE_FLAG, fieldName));
                }
            }
            ExcelWriter excelWriter = new ExcelWriterBuilder()
                    .excelType(ExcelTypeEnum.XLSX)
                    .head(headers)
                    .file(outputStream)
                    .build();
            WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();
            ArrayList<List<String>> cols = new ArrayList<>();
            cols.add(fieldFlagNames);
            excelWriter.write(cols, writeSheet);
            excelWriter.finish();
            //上传到oss
            final byte[] byteArray = outputStream.toByteArray();
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
            AliYunOssUtil.X.upload(FileExportConstant.OSS_DOWNLOAD_FILE_TEMPLATE_DIR + ossKey, byteArrayInputStream);
            byteArrayInputStream.close();
        } catch (Exception e) {
            log.error("上传模板文件失败,", e);
            throw new BusinessException(DownloadResultCode.CREATE_TEMPLATE_FILE_ERROR);
        }
    }
}
